<template>
  <div class="p-2">
    <!-- 保持搜索表单在最上方 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!-- 原有表单内容（未修改） -->
            <el-form-item label="股票代码" prop="symbol">
              <el-input v-model="queryParams.symbol" placeholder="请输入股票代码" clearable @keyup.enter="handleQuery">
                <template #append>
                  <el-popover v-model:visible="showSymbols" placement="bottom" :width="200" trigger="manual"
                    :persistent="false">
                    <template #reference>
                      <el-button icon="ArrowDown" @click.stop="togglePopover" />
                    </template>
                    <el-select v-model="queryParams.symbol" @change="handleSymbolSelect" filterable
                      :value-key="'symbol'">
                      <el-option v-for="symbol in symbolOptions" :key="symbol" :label="symbol" :value="symbol" />
                    </el-select>
                  </el-popover>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 表格区域保持在中间 -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="marketList" @selection-change="handleSelectionChange"
        @sort-change="handleSortChange">
        <!-- 原有表格列（未修改） -->
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" v-if="true" />
        <el-table-column label="公司名称" align="center" prop="cname" />
        <el-table-column label="行业分类" align="center" prop="category" />
        <el-table-column label="股票代码" align="center" prop="symbol" />
        <el-table-column label="最新价" align="center" prop="price" />
         <el-table-column 
    label="日期" 
    prop="time" 
    :formatter="(row) => row.time?.substring(0, 10)" 
  />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="买入分析" placement="top">
              <el-button link type="primary" icon="ShoppingCart" @click="handleBuy(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="false" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 调整AI问答区域到表格下方 -->
    <div class="chat-container">
    
      <el-card 
       v-if="response || isAnalyzing"
        class="response-container"
        shadow="always"
        body-style="padding: 20px"
      >
        <h3>分析结果：</h3>
       <!-- 加载中时显示提示 -->
  <div v-if="isAnalyzing" class="response-content text-center">正在分析中，请稍候...</div>
  <!-- 加载完成后显示结果 -->
  <div v-else class="response-content" v-html="formattedResponse"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup name="Market" lang="ts">
import { listMarket, listSymbols } from '@/api/market/market';
import { MarketVO, MarketQuery, MarketForm } from '@/api/market/market/types';

import axios from 'axios';
import { ref, computed } from 'vue';
import { marked } from 'marked';           // 新增Markdown解析
import './index.css';                       // 新增样式文件（需确保文件存在）

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const marketList = ref<MarketVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
// 新增：加载状态控制变量
const isAnalyzing = ref(false);
const queryFormRef = ref<ElFormInstance>();
// 提取环境变量为独立常量（新增）
const BASE_API = import.meta.env.VITE_APP_BASE_API;
const initFormData: MarketForm = {
  id: undefined,
  cname: undefined,
  category: undefined,
  symbol: undefined,
  price: undefined,
  time: undefined
};
const data = reactive<PageData<MarketForm, MarketQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 1,  // 修改：只获取1条数据
    cname: undefined,
    category: undefined,
    symbol: undefined,
    price: undefined,
    time: undefined,
    sortField: 'time',  // 新增：按时间字段排序
    sortOrder: 'desc',  // 新增：降序排列（最新的在前）
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form} = toRefs(data);

/** 查询Market信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMarket(queryParams.value);
  marketList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
// 修改重置查询方法（可选优化）
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 重置时保持分页和排序规则
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 1;
  queryParams.value.sortField = 'time';
  queryParams.value.sortOrder = 'desc';
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MarketVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

// 新增响应式变量和方法
const symbolOptions = ref<string[]>([]);
const showSymbols = ref(false);

// 修改后的 loadSymbols 方法
const loadSymbols = async () => {
  try {
    if (symbolOptions.value.length === 0) {
      const res = await listSymbols();
      symbolOptions.value = res.data;
    }
    showSymbols.value = true; // 数据加载完成后，强制显示弹出层
  } catch (error) {
    console.error('加载股票代码失败', error);
    proxy?.$modal?.msgError('股票代码加载失败');
  }
};

const handleSymbolSelect = () => {
  showSymbols.value = false; // 确保选择时关闭下拉框
  handleQuery(); // 执行搜索
};

// 修改 togglePopover 方法
const togglePopover = () => {
  loadSymbols(); // 点击箭头时直接触发数据加载
};

// 处理排序事件
const handleSortChange = ({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) => {
  // 确保每次点击排序时重置到第一页
  queryParams.value.pageNum = 1;

  // 更新排序字段和排序方向
  queryParams.value.sortField = prop; // prop 是列的字段名，比如 'time'
  queryParams.value.sortOrder = order ? (order === 'ascending' ? 'asc' : 'desc') : undefined;

  // 重新调用获取数据的函数，传递排序的参数
  getList();
  console.log('Sort Params:', queryParams.value.sortField, queryParams.value.sortOrder); // 调试输出
};

onMounted(() => {
  getList();
});

// 修改 handleBuy 方法，添加加载状态控制
const handleBuy = async (row: MarketVO) => {
  const symbol = row.symbol;
  const message = `分析一下${symbol}股票的趋势`;
   const url = `${BASE_API}/ChatAssistant2?message=${encodeURIComponent(message)}`;

  isAnalyzing.value = true; // 开始分析，标记为加载中
  try {
    const res = await axios.get(url);
    response.value = res.data;
    proxy?.$modal.msgSuccess(`已请求分析${symbol}的趋势`);
  } catch (err) {
    console.error('分析请求失败:', err);
    proxy?.$modal.msgError('发送分析请求失败，请稍后再试');
  } finally {
    isAnalyzing.value = false; // 无论成功/失败，结束加载状态
  }
};

const response = ref<string | null>(null);

// 新增：配置Markdown解析规则
marked.setOptions({
  breaks: true,   // 换行转<br>
  gfm: true,      // 启用GitHub Flavored Markdown
  sanitize: true  // 清理HTML（防止XSS）
});

// 新增：计算属性格式化响应内容（支持Markdown）
const formattedResponse = computed(() => {
  return marked.parse(response.value || '暂无分析结果');
});
</script>
